﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace MediaAutomatorLib.Helpers
{
    public static class FileRecognizer
    {
        public enum FileType
        {
            Movie,
            TvShow,
            Undefined
        }

        private static readonly Regex TvShowRegex = new Regex("s\\d{1,2}e\\d{1,2}", RegexOptions.IgnoreCase);
        private static readonly Regex VideoSampleRegex = new Regex("sample", RegexOptions.IgnoreCase);
        private static string GetContentType(string fileName)
        {
            string contentType = "application/octetstream";
            string extension = System.IO.Path.GetExtension(fileName);
            if (extension != null)
            {
                string ext = extension.ToLower();
                if (ext.Equals(".mkv"))
                    contentType = "video/mkv";
                else
                {
                    Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
                    if (registryKey != null && registryKey.GetValue("Content Type") != null)
                        contentType = registryKey.GetValue("Content Type").ToString();                    
                }
            }

            return contentType;
        }

        public static FileType Recognize(string filename)
        {            
            if (IsVideo(filename)) {
                if(IsTvShow(filename))
                    return FileType.TvShow;
                if (!IsVideoSample(filename))
                    return FileType.Movie;
            }
            return FileType.Undefined;
        }

        private static bool IsVideo(String fileName)
        {
            return GetContentType(fileName).StartsWith("video");
        }

        private static bool IsVideoSample(String fileName)
        {
            return VideoSampleRegex.IsMatch(fileName);
        }

        private static bool IsTvShow(String fileName)
        {
            return TvShowRegex.IsMatch(fileName);
        }

    }
}
